<template>
  <!-- 操作推窗 -->
  <BaseDrawer
    width="50%"
    :title="drawerTitle"
    placement="right"
    v-model:visible="open"
    :maskClosable="false"
    @close="handleClose"
  >
    <template #default>
      <a-form
        v-if="open"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="12" v-show="formState.parentId !== 0">
            <a-form-item
              :label="t('routes.dept.superiorDepartment')"
              name="parentId"
            >
              <treeselect
                ref="treeRef"
                class="!mt-[3px]"
                v-model:value="formState.parentId"
                :normalizer="normalizer"
                :placeholder="t('routes.dept.superiorDepartmentPlaceholder')"
                :options="deptOptions"
                @select="handleTreeSelect"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dept.deptName')" name="deptName">
              <a-input
                v-model:value="formState.deptName"
                :placeholder="t('routes.dept.deptNamePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dept.orderNum')" name="orderNum">
              <a-input-number
                class="!w-[100%]"
                v-model:value="formState.orderNum"
                :placeholder="t('routes.dept.orderNumPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dept.status')" name="status">
              <a-radio-group
                v-model:value="formState.status"
                :options="disableOptions"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template #footer>
      <a-button type="primary" class="mr-3" @click="handleSubmit">
        {{ t("common.okText") }}
      </a-button>
      <a-button @click="handleClose">{{ t("common.cancelText") }}</a-button>
    </template>
  </BaseDrawer>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, nextTick } from "vue";
import {
  Row,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  RadioGroup,
} from "ant-design-vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import {
  getDept,
  getDeptById,
  addDept,
  updateDept,
} from "@/api/admin/system/dept";
import BaseDrawer from "@/components/BaseDrawer/index.vue";
import { handleTree } from "@/utils/tools";
import { useUserStore } from "@/store/modules/user";
import { message as Message } from "ant-design-vue";
import Treeselect from "vue3-treeselect";
import { formRules } from "@/utils/validate";
import useDrawer from "@/hooks/useDrawer";
import "vue3-treeselect/dist/vue3-treeselect.css";
import { IDept } from "@/api/admin/system/dept/type";
import { IData } from "@/api/admin/system/dict/data/type";
import { getDict } from "@/utils/dictFormat";
import { useI18n } from "@/hooks/useI18n";

const { t } = useI18n();

interface FormState {
  deptId: undefined | number;
  parentId: undefined | number;
  deptName: undefined | string;
  orderNum: string | number;
  status: string;
}
type optionType = "add" | "update";

export default defineComponent({
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input-number": InputNumber,
    "a-radio-group": RadioGroup,
    "a-input": Input,
    Treeselect,
    BaseDrawer,
  },
  emits: ["finished"],
  setup(props, { expose, emit }) {
    const disableOptions = ref<IData[]>([]);
    const userStore = useUserStore();
    const treeRef = ref();
    const rules = {
      parentId: [
        {
          required: true,
          validator: formRules.number,
          message: t("routes.dept.superiorDepartmentCannotBeBlank"),
          trigger: "change",
        },
      ],
      deptName: [
        {
          required: true,
          message: t("routes.dept.deptNameCannotBeBlank"),
          trigger: "blur",
        },
      ],
      orderNum: [
        {
          required: true,
          validator: formRules.number,
          message: t("routes.dept.orderNumCannotBeBlank"),
          trigger: "blur",
        },
      ],
    };
    const formRef = ref();
    const normalizer = (node) => {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    };

    // 获取部门树
    const deptOptions = ref<IDept[]>([]);
    const deptList = ref<IDept[]>([]);
    const formState: FormState = reactive({
      deptId: undefined,
      parentId: undefined,
      deptName: undefined,
      orderNum: "1",
      status: "1",
    });
    // 上级部门选中事件
    const handleTreeSelect = (node) => {
      formState.parentId = node.deptId;
    };

    // 取消推窗
    const { open, drawerTitle, handleOpenDrawer, handleCloseDrawer } =
      useDrawer();
    const handleClose = (cb?: () => void) => {
      handleCloseDrawer.value(() => {
        formState.deptId = undefined;
        formRef.value.resetFields();
        cb && typeof cb === "function" && cb();
      });
    };
    // 显示推窗
    const handleShow = (type: optionType, row?: IDept) => {
      handleOpenDrawer.value(() => {
        if (row && type === "update") {
          getDept().then((res) => {
            res.data.rows.forEach((item) => {
              if (item.deptId === row.deptId) {
                item.isDisabled = true;
              } else {
                item.isDisabled = false;
              }
            });
            const children = handleTree(
              res.data.rows,
              "deptId",
              "parentId",
              "children",
              userStore.userInfo.deptId
            ).tree;
            const parent = res.data.rows.filter(
              (item) => item.deptId === userStore.userInfo.deptId
            );
            parent[0].children = children;
            deptList.value = parent;
            deptOptions.value = parent;

            getDeptById(row.deptId).then((res) => {
              open.value = true;
              drawerTitle.value = t("common.update");
              nextTick(() => {
                Object.keys(formState).forEach((key) => {
                  formState[key] = res.data[key];
                });
                treeRef.value.forest.selectedNodeIds.push(res.data.parentId);
              });
            });
          });
        } else {
          getDept().then((res) => {
            res.data.rows.forEach((item) => {
              item.isDisabled = false;
            });
            const children = handleTree(
              res.data.rows,
              "deptId",
              "parentId",
              "children",
              userStore.userInfo.deptId
            ).tree;
            const parent = res.data.rows.filter(
              (item) => item.deptId === userStore.userInfo.deptId
            );
            parent[0].children = children;
            deptList.value = parent;
            deptOptions.value = parent;

            open.value = true;
            drawerTitle.value = t("common.add");
            if (row != null && row.deptId) {
              nextTick(() => {
                formState.parentId = row.deptId;
                if (treeRef.value) {
                  treeRef.value.forest.selectedNodeIds.push(row.deptId);
                }
              });
            }
          });
        }
      });
    };

    // 表单提交
    const handleSubmit = () => {
      console.log(formState);
      formRef.value
        .validate()
        .then(() => {
          if (formState.deptId) {
            updateDept(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          } else {
            addDept(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          }
        })
        .catch((error: ValidateErrorEntity) => {
          console.log("error", error);
        });
    };

    onMounted(async () => {
      disableOptions.value = await getDict("sys_normal_disable");
      disableOptions.value.forEach((item) => {
        item.label = item.dictLabel;
        item.value = item.dictValue;
      });
    });

    expose({
      handleShow,
    });
    return {
      t,
      open,
      drawerTitle,
      handleClose,
      handleSubmit,
      formState,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      normalizer,
      deptOptions,
      rules,
      formRef,
      treeRef,
      handleTreeSelect,
      disableOptions,
    };
  },
});
</script>
